package com.hs.singleton;

import java.io.ObjectStreamException;
import java.io.Serializable;
import java.util.Random;

/**
 * @Author: hs
 * @Description:  不同的地方在饿汉式方式是只要Singleton类被装载就会实例化，没有Lazy-Loading的作用，而静态内部类方式在Singleton类被装载时并不会立即实例化，
 * 而是在需要实例化时，调用getInstance方法，才会装载SingletonInstance类，从而完成Singleton的实例化
 * 优点：避免了线程不安全，延迟加载，效率高
 * @Date: Create in 18:51 2019/7/28
 */

public class SingletonInnerClass  implements Serializable {

    private static final long serialVersionUID = 111111L;
    //原因是因为常量值存(final)储在JVM内存中的常量区中，在类不加载时即可访问
    public static final long  testLong = 111111L;
    public static long  testLong1 = 111111L;
    public static String  testLong2;
    //如果常量值必须在运行时才能确定，如常量值是一个随机值，也会引起类的加载 (初始化)
    public static final int FINAL_VALUE_INT = new Random(66).nextInt();
    static {
        System.out.println(SingletonInnerClass.class+"被加载supper。。。");
    }
    private SingletonInnerClass() {}

    private static class SingletonInstance {
        static {
            System.out.println(SingletonInstance.class+"被加载sub。。。");
        }
        private static final SingletonInnerClass INSTANCE = new SingletonInnerClass();
    }
    public static void testMethod() {
        System.out.println("调用方法...");
    }
    public static SingletonInnerClass getInstance() {
        return SingletonInstance.INSTANCE;
    }

    protected Object readResolve() throws ObjectStreamException {
        System.out.println("调用了readResolve方法！");
        return SingletonInstance.INSTANCE;
    }


}
